import requests
import json, os
from .spider import *


class Fh:
    def __init__(self):
        pass

    def chapter(self, arg1, arg2):
        '''
        19, 19698
        :return:{'novel_name': '三国重生马孟起', 'novel_author': '夏海苍松',
        'novel_author_url': None, 'novel_intro': '本书简介：    关于三国重生马孟起：',
        'novel_type': '现言(三国重生马孟起)', 'refresh_time': '(10-22)',
        'novel_status': None, 'novel_words': None,
        'novel_img': 'https://www.fhxiaoshuo.com/files/article/image/19/19698/19698s.jpg',
        'latest_chapter': '第八一六章 战事毕冀州事宜（二）','latest_chapter_url': 'https://www.fhxiaoshuo.com/read/19/19698/36970756.shtml',
        'novel_chapter_info': {'第一章 马腾喜得麟儿': 'https://www.fhxiaoshuo.com/read/19/19698/2619167.shtml',...}}
        '''
        url = 'https://www.fhxiaoshuo.com/read/{}/{}'.format(arg1, arg2)
        # print(Spider(url).html)
        novel_info = '<div id="info">.*?<h1>(.*?)</h1>.*?<p>作.*?者：(.*?)</p>.*?<p>类.*?别：(.*?)</p>'
        novel_author_url = None
        novel_intro = '<p class="introtxt">(.*?)<br />'
        refresh_time = '<p>更新时间：<font color=\'blue\'>(.*?)【TXT下载请使用鼠标右键下载地址然后目标另存为】</font></p>'
        novel_status = None
        novel_words = None
        novel_img = '<div id="fmimg"><img alt=".*?" src="(.*?)"/></div>'
        latest_chapter = '<p>最新连载：<a href=".*?" target="_blank">(.*?)</a></p>'
        latest_chapter_url = '<p>最新连载：<a href="(.*?)" target="_blank">.*?</a></p>'
        chapter_info = '<dd><a href="(.*?)" target="_blank">(.*?)</a></dd>'
        novel_dict_info = Spider(url).info(novel_name=novel_info,
                                           novel_intro=novel_intro,
                                           refresh_time=refresh_time,
                                           novel_img=novel_img,
                                           latest_chapter=latest_chapter,
                                           latest_chapter_url=latest_chapter_url,
                                           novel_chapter_info=chapter_info, )
        chapter_num = len(novel_dict_info['novel_chapter_info']) // 3
        novel_chapter_info = {}
        for i in range(chapter_num):
            novel_chapter_info[novel_dict_info['novel_chapter_info'][i * 3 + 2][1]] = \
                novel_dict_info['novel_chapter_info'][i * 3 + 2][0]
            novel_chapter_info[novel_dict_info['novel_chapter_info'][i * 3 + 1][1]] = \
                novel_dict_info['novel_chapter_info'][i * 3 + 1][0]
            novel_chapter_info[novel_dict_info['novel_chapter_info'][i * 3][1]] = \
                novel_dict_info['novel_chapter_info'][i * 3][0]
        if len(novel_dict_info['novel_chapter_info']) - len(novel_dict_info) == 1:
            novel_chapter_info[novel_dict_info['novel_chapter_info'][-1][1]] = \
                novel_dict_info['novel_chapter_info'][-1][0]
        else:
            novel_chapter_info[novel_dict_info['novel_chapter_info'][-1][1]] = \
                novel_dict_info['novel_chapter_info'][-1][0]
            novel_chapter_info[novel_dict_info['novel_chapter_info'][-2][1]] = \
                novel_dict_info['novel_chapter_info'][-2][0]
        # print(novel_chapter_info)
        novel_dict = {
            'novel_name': novel_dict_info['novel_name'][0][0],
            'novel_author': novel_dict_info['novel_name'][0][1],
            'novel_author_url': None,
            'novel_intro': novel_dict_info['novel_intro'][0],
            'novel_type': novel_dict_info['novel_name'][0][2],
            'refresh_time': novel_dict_info['refresh_time'][0],
            'novel_status': None,
            'novel_words': None,
            'novel_img': novel_dict_info['novel_img'][0],
            'latest_chapter': novel_dict_info['latest_chapter'][0],
            'latest_chapter_url': novel_dict_info['latest_chapter_url'][0],
            'novel_chapter_info': novel_chapter_info, }
        return novel_dict

    def content(self, arg1, arg2, arg):
        '''
        19, 19698, 2619182
        :return: {'chapter_name': ' 第十三章 精锐营孟起练兵',
        'chapter_content': '\r\n\t\t<!--go-->\r\n\t\t\r\n\t\t    “那百长您今年多大？”小耗子接着问道。... '
        'novel_name': '三国重生马孟起', 'novel_author': None, 'novel_words': None,
        'novel_catalog': 'https://www.fhxiaoshuo.com/read/19/19698/',
        'pre_chapter': 'https://www.fhxiaoshuo.com/read/19/19698/2619181.shtml',
        'next_chapter': 'https://www.fhxiaoshuo.com/read/19/19698/2619183.shtml'}
        '''
        url = 'https://www.fhxiaoshuo.com/read/{}/{}/{}.shtml'.format(arg1, arg2, arg)
        print(Spider(url).html)
        chapter_name = '<div class="zhangjieming">.*?<h1>(.*?)</h1>'
        chapter_content = '<script language="javascript" type="text/javascript" src=".*?"></script></div>(.*?)<div class="bottem">'
        novel_name = '<div class="con_top"><script type="text/javascript" src=".*?"></script><a href=".*?">凤凰小说网</a>.*?<a href=".*?">(.*?)</a>'
        novel_author = None
        novel_words = None
        novel_catalog = '投推荐票</a><a href="(.*?)">上一章</a><a href="(.*?)" title=".*?">章节目录</a><a href="(.*?)">下一章</a>'
        content_info = Spider(url).info(chapter_name=chapter_name,
                                        chapter_content=chapter_content,
                                        novel_name=novel_name,
                                        novel_catalog=novel_catalog, )
        chapter_info = {
            'chapter_name': content_info['chapter_name'][0],
            'chapter_content': content_info['chapter_content'][0],
            'novel_name': content_info['novel_name'][0],
            'novel_author': novel_author,
            'novel_words': novel_words,
            'novel_catalog': content_info['novel_catalog'][0][1],
            'pre_chapter': content_info['novel_catalog'][0][0],
            'next_chapter': content_info['novel_catalog'][0][2],
        }
        print(chapter_info)
        return chapter_info


# x = Fh().content(19, 19698, 2619182)


class FhSearch:
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}

    def __init__(self):
        pass

    def search_book(self, keyworld):
        '''
        :return: {'万道大主宰': {'novel_author_url': None, 'novel_url': 'https://www.fhxiaoshuo.com/read/139/139435/',
         'latest_chapter': ' 第263章 大佬会谈！',
         'latest_chapter_url': 'https://www.fhxiaoshuo.com/read/139/139435/37010816.shtml',
         'novel_type': None, 'refresh_time': '18-10-22',
        'novel_status': '连载', 'novel_author': '清十依', 'novel_words': '1573K'},...}
        '''
        keyworld = keyworld.encode('gb2312')
        url = 'https://www.fhxiaoshuo.com/modules/article/search.php'
        params = {
            'searchkey': keyworld,
        }
        res = requests.get(url, params=params, headers=self.headers, verify=False)
        res.encoding = 'gbk'
        if res.history:
            return {'url': res.url}
        else:
            search_url = res.url
            novel_name = '<td class="odd"><a href="(.*?)">(.*?)</a></td>'
            novel_author = '</td>.*?<td class="odd">(.*?)</td>'
            novel_author_url = None
            latest_chapter = '<td class="even"><a href="(.*?)" target="_blank">(.*?)</a></td>'
            novel_type = None
            refresh_time = '<td class="odd" align="center">(.*?)</td>'
            novel_status = '<td class="even" align="center">(.*?)</td>'
            novel_words = '<td class="even">(.*?)</td>'
            novel_img = None
            search_info = Spider(search_url).info(
                novel_name=novel_name,
                novel_author=novel_author,
                latest_chapter=latest_chapter,
                refresh_time=refresh_time,
                novel_status=novel_status,
                novel_words=novel_words,
            )
            # print(search_info['novel_words'])
            search_dict = {}
            for i in range(len(search_info['novel_name']))[:10]:
                novel_dict = {}
                novel_dict['novel_author_url'] = novel_author_url
                novel_dict['novel_url'] = search_info['novel_name'][i][0]
                novel_dict['latest_chapter'] = search_info['latest_chapter'][i][1]
                novel_dict['latest_chapter_url'] = search_info['latest_chapter'][i][0]
                novel_dict['novel_type'] = novel_type
                novel_dict['refresh_time'] = search_info['refresh_time'][0]
                novel_dict['novel_status'] = search_info['novel_status'][0]
                novel_dict['novel_author'] = search_info['novel_author'][i * 2]
                search_dict[search_info['novel_name'][i][1]] = novel_dict
                if i == 0:
                    novel_dict['novel_words'] = search_info['novel_words'][i + 1]
                else:
                    novel_dict['novel_words'] = search_info['novel_words'][i * 2 + 1]
            print(search_dict)
            return search_dict

    def home(self):
        '''前五个
        :return: {'当我们深深爱上一个人': {'novel_author': '林西先生', '
        novel_author_url': None, 'novel_url': 'https://www.fhxiaoshuo.com/read/152/152097/',
        'novel_intro': None, 'novel_type': '[古言]', 'refresh_time': '10-23', 'novel_status': None,
        'novel_words': None, 'novel_img': None, 'latest_chapter': '第67章 一面示弱，一面示威。', '
        latest_chapter_url': 'https://www.fhxiaoshuo.com/read/152/152097/37174824.shtml'},...}
        '''
        url = 'https://www.fhxiaoshuo.com/'
        novel_name = '<span class="s2"><a href="(.*?)" target="_blank">(.*?)</a></span>'
        novel_author = '<span class="s4">(.*?)</span>'
        novel_author_url = None
        novel_intro = None
        novel_type = '<li><span class="s1">(.*?)</span>'
        refresh_time = '<span class="s5">(.*?)</span>'
        novel_status = None
        novel_words = None
        novel_img = None
        latest_chapter = '<span class="s3"><a href="(.*?)" target="_blank">(.*?)</a></span>'
        home_info = Spider().info(
            novel_name=novel_name,
            novel_author=novel_author,
            novel_type=novel_type,
            refresh_time=refresh_time,
            latest_chapter=latest_chapter,
        )
        # print(home_info)
        home_dict = {}
        for i in range(len(home_info['novel_name']))[:5]:
            novel_content = {
                'novel_author': home_info['novel_author'][i],
                'novel_author_url': novel_author_url,
                'novel_url': home_info['novel_name'][i][0] ,
                'novel_intro': novel_status,
                'novel_type': home_info['novel_type'][i],
                'refresh_time': home_info['refresh_time'][i],
                'novel_status': novel_status,
                'novel_words': novel_words,
                'novel_img': novel_img,
                'latest_chapter': home_info['latest_chapter'][i][1],
                'latest_chapter_url': home_info['latest_chapter'][i][0]
            }
            home_dict[home_info['novel_name'][i][1]] = novel_content
        # print(home_dict)
        return home_dict

x = FhSearch().home()
